package com.dmall.directed.graph;

/**
 * @author: xiao1.wang
 * @date: 2022/9/3 23:44
 */
public class DirectedCycleDetection {
    private Graph G;
    private boolean[] visited;
    private boolean[] onPath;
    private boolean hasCycle;

    public DirectedCycleDetection(Graph G) {
        if (!G.isDirected()) {
            throw new IllegalArgumentException("DirectedCycleDetection only works in directed graph.");
        }
        this.G = G;
        this.visited = new boolean[G.V()];
        this.onPath = new boolean[G.V()];
        this.hasCycle = false;

        for (int i = 0; i < G.V(); i++) {
            if (!visited[i]) {
                if (dfs(i, i)) {
                    hasCycle = true;
                    break;
                }
            }
        }
    }

    private boolean dfs(int v, int p) {
        visited[v] = true;
        onPath[v] = true;
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            } else {
                if (onPath[w]) {
                    return true;
                }
            }
        }
        onPath[v] = false;
        return false;
    }

    public boolean hasCycle() {
        return hasCycle;
    }

    public static void main(String[] args) {
        String filename = BellmanFord.class.getClassLoader().getResource("com/dmall/directed/graph/ug.txt").getPath();
        Graph g = new Graph(filename, true);
        DirectedCycleDetection dcd = new DirectedCycleDetection(g);
        System.out.println(dcd.hasCycle());
    }
}
